package com.zhijian.medical.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhijian.medical.dao.local.FishSampleReadyMapper;
import com.zhijian.medical.entity.po.*;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.enums.*;
import com.zhijian.medical.exception.BusinessException;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author li xiao dong
 * @since 2022-08-12
 */
@Service
public class FishSampleReadyServiceImpl extends ServiceImpl<FishSampleReadyMapper, ExperimentFishSampleReady> implements FishSampleReadyService {

    @Autowired
    private FishSampleReadyMapper sampleReadyMapper;
    @Autowired
    private FishSampleOplogService sampleOplogService;

    @Autowired
    private FishService fishService;

    @Autowired
    private ExperimentProcessSampleService sampleService;

    @Autowired
    private ExperimentProcessSampleLogService sampleLogService;

    @Override
    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    public Boolean create(ExperimentFishSampleReady experimentFishSampleReady) {
        Long readyId = insert(experimentFishSampleReady);
        for (ExperimentFishSampleOplog sampleOplog : experimentFishSampleReady.getCzjl()) {
            sampleOplog.setReadyId(readyId);
            sampleOplogService.insert(sampleOplog);
            updateSampleStatus(sampleOplog);
        }

        // 修改实验状态
        ExperimentFish experimentFish = ExperimentFish.builder().id(experimentFishSampleReady.getFishId()).status(ExperimentFishStatusEnum.YBCL.getCode().byteValue()).build();
        fishService.updateByPrimaryKeySelective(experimentFish);

        List<ExperimentProcessSampleVo> sampleVoList = sampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.FISH.getCode().byteValue())
                .experimentProcessId(experimentFishSampleReady.getFishId())
                .build());
        ExperimentFish fish = fishService.detail(experimentFishSampleReady.getFishId());
        sampleLogService.saveBatch(sampleVoList.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(experimentFishSampleReady.getFishId())
                .mainType(ExperimentTypeEnum.FISH.getCode().byteValue())
                .op(String.format("%s%s-%s", fish.getName(), fish.getExperimentNum(), ExperimentFishStatusEnum.YBCL.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));

        return true;
    }


    public Boolean updateSampleStatus(ExperimentFishSampleOplog sampleOplog) {
        String clfs = sampleOplog.getClfs();
        if (StrUtil.isBlankIfStr(clfs)) {
            return true;
        }
        byte status = 0;
        if (clfs.equals(ExperimentFishClfsEnum.CXSY.getCode())) {
            status = 4;
        }
        if (clfs.equals(ExperimentFishClfsEnum.CXJC.getCode())) {
            status = 5;
        }
        if (clfs.equals(ExperimentFishClfsEnum.TF.getCode())) {
            status = 8;
        }

        if (status == 0) {
            return true;
        }
        ExperimentProcessSample processSample = new ExperimentProcessSample();
        processSample.setMoleculePathologyNumber(sampleOplog.getFzblh());
        processSample.setStatus(status);
        return sampleService.updateByPrimaryKeySelective(processSample);

    }

    @Override
    public Long insert(ExperimentFishSampleReady experimentFishSampleReady) {
        deleteSampleByFishId(experimentFishSampleReady.getFishId());
        int count = sampleReadyMapper.insert(experimentFishSampleReady);
        if (count <= 0) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "样本处理区创建失败");
        }
        return experimentFishSampleReady.getId();
    }

    public Boolean deleteSampleByFishId(Long fishId) {
        delete(fishId);
        sampleOplogService.delete(fishId);
        return true;
    }

    public Boolean delete(Long fishId) {
        QueryWrapper<ExperimentFishSampleReady> experimentFishSampleReadyQueryWrapper = new QueryWrapper<>();
        experimentFishSampleReadyQueryWrapper.eq("fish_id", fishId);
        return sampleReadyMapper.delete(experimentFishSampleReadyQueryWrapper) > 0;
    }

    @Override
    public ExperimentFishSampleReady detail(Long fishId) {
        QueryWrapper<ExperimentFishSampleReady> experimentFishSampleReadyQueryWrapper = new QueryWrapper<>();
        experimentFishSampleReadyQueryWrapper.eq("fish_id", fishId);
        ExperimentFishSampleReady sampleReady = sampleReadyMapper.selectOne(experimentFishSampleReadyQueryWrapper);
        if (sampleReady == null) {
            sampleReady = new ExperimentFishSampleReady();
        }
        sampleReady.setCzjl(sampleOplogService.list(fishId));

        ExperimentFish experimentFish = fishService.selectByPrimaryKey(fishId);
        sampleReady.setResult(experimentFish.getStatus() >= ExperimentFishStatusEnum.YBCL.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        sampleReady.setResultStr(experimentFish.getStatus() >=ExperimentFishStatusEnum.YBCL.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        return sampleReady;
    }

}
